package com.karolak.sm.context;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.karolak.sm.event.Event;
import com.karolak.sm.state.State;
import com.karolak.sm.state.StateId;
import com.karolak.sm.state.Transition;

public class StateConfig {

	private Log log = LogFactory.getLog(getClass());

	private Map<StateId, State> states;

	private Map<Event, Transition> transitionByEventIx;

	public StateConfig() {
		states = new ConcurrentHashMap<StateId, State>();
		transitionByEventIx = new ConcurrentHashMap<Event, Transition>();
	}

	public State getState(StateId stateId) {
		return getStates().get(stateId);
	}

	public Transition getTransition(Event event) {
		return getTransitionByEventIx().get(event);
	}

	public void registerStates(List<State> states) {
		if (states == null) {
			return;
		}
		for (State state : states) {
			register(state);
		}
	}

	public void registerTransitions(List<Transition> transitions) {
		if (transitions == null) {
			return;
		}
		for (Transition transition : transitions) {
			register(transition);
		}
	}

	public void register(State state) {
		if (state == null) {
			return;
		}
		getStates().put(state.getStateId(), state);
		log.info(String.format("Registering state:%s.", state.getStateId()));
	}

	public void register(Transition transition) {
		if (transition == null) {
			return;
		}
		getTransitionByEventIx().put(transition.getEvent(), transition);
		log.info(String.format("Registering transition:%s.", transition));
	}

	// === get/set === //
	public Map<StateId, State> getStates() {
		return states;
	}

	protected Map<Event, Transition> getTransitionByEventIx() {
		return transitionByEventIx;
	}
}
